<!DOCTYPE html>
<html class="Content">
<head>
    <title>xUnit.js: Mocks &amp; Stubs</title>
    <link type="text/css" rel="Stylesheet" href="../../Style/documentation.css" />
</head>
<body>
    <h1>Mocks &amp; Stubs</h1>
    <p>
        <strong>Mocks</strong> provide an execution context wherein a given member (property or method) of a known object is overridden with a temporary substitute. 
        When invoked, the mocked value will be available in the scope of the function delegate that is passed into the mock. After the delegate completes execution, the 
        mock is cleaned up, and the member is reverted to its previous state. Mocks are useful for injecting code dependencies and stub implementations, and help 
        to identify and isolate boundary crossing events when designing production code. The global object, typically the host engine (i.e., the top level <em>this</em>; 
        in the case of a browser, roughly analogous to the <em>window</em> object reference) is available at any depth as the result of the method Object.Global(). 
        So, to, e.g., mock <em>window.open()</em>, we could override the <em>window</em> reference on the host engine:
        <span class="Code">
function OverridesWindowOpenMethod(){
    // Arrange
    var mockWindow=<strong>Mocks.GetMock</strong>(Object.Global(),"window",{open:function(targetUrl){
        actual=targetUrl;
    }});
    var expected="expected";
    var actual=null;

    //Act
    <strong>mockWindow(function(){</strong>
        window.open(expected);
    <strong>})</strong>

    //Assert
    Assert.Equal(expected,atual);
}        
        </span> 
    </p>
    <p>
        <strong>Stubs</strong> are an instrumented object mapping system, for creating complex hierarchies, interfaces, and object shapes to meet the 
        expectations of production APIs. The instrumentation automatically captures invocations of stub methods, arguments supplied, and provides well-known return values,
        which can be easily changed as the test requires. Thus, the above fact could be rewritten thusly:
        <span class="Code">
function OverridesWindowOpenMethod(){
    // Arrange
    var stubWindow=<strong>Stubs.GetObject</strong>({open:{parameters:["targetUrl"]}});
    var expected="expected";
    var actual=null;

    //Act
    <strong>stubWindow</strong>.open(expected);
    actual=<strong>stubWindow</strong>.open.Calls[0].Arguments.targetUrl;

    //Assert
    Assert.Equal(expected,atual);
}        
        </span> 
    </p>
    <p>
        Mocks and Stubs are frequently used together, and can be used to provide complex, host-specific environments, such as a DOM implementation, or a database or server abstraction.
    </p>
</body>
</html>